package com.qf.sy2103.seckill.service.impl;

import com.qf.sy2103.seckill.dao.TbBooksMapper;
import com.qf.sy2103.seckill.entity.TbBooks;
import com.qf.sy2103.seckill.service.SeckillServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillServcie {

    @Autowired
    TbBooksMapper tbBooksMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized boolean bookSeckill(Integer id) {

        // 1. 判断书的库存量
        final TbBooks book = tbBooksMapper.selectByPrimaryKey(id);
        // 使用mysql数据库的行锁
        // 这里会增加数据库服务的压力，更推荐使用java中的同步方式
//        final TbBooks book = tbBooksMapper.selectForUpdate(id);
        final Integer bookNum = book.getBookNum();
        if (bookNum>0){
            int remainNum =bookNum-1;
            // 生成创建订单的消息
            log.info("秒杀成功，当前书的数量为{},秒杀后剩余{}",bookNum,remainNum);
            // 减少库存
            book.setBookNum(remainNum);
            tbBooksMapper.updateByPrimaryKey(book);
            return true;
        }else {
            log.info("秒杀失败，当前数的数量为{}",bookNum);
            return false;
        }


    }
}
